import util from '../../../../utils/utils';
import data from "../../../../utils/data";
import Dialog from '../../../../dist/dialog/dialog';
import bmap from '../../../../utils/bmap-wx.min';

const PHOME_REG = /^[1][0-9]{10}$/

Page({
  /**
   * 页面的初始数据
   */
  BMap:null,
  data: {
    openArea: false,
    pass: false,
    addr_id: 0,
    modify: false,
    detail: {
      addr_id: 0,
      longitude: 0,
      latitude: 0,
      province: '',
      gender: '1',
      active: '1',
      city: '',
      county: '',
      detailinfo: '',
      phone_number: '',
      user_name: '',
      area_info: '选择地址',
      address_tag: '',
    },
  },

  initPage: function (options) {
    let self = this;
    let _data;
    if (options.detail) {
      _data = JSON.parse(options.detail);
      _data.area_info = [
        _data.province,
        _data.city,
        _data.county
      ].join('');
      _data['gender'] = _data['gender'] + '';
      self.setData({
        modify: true,
        addr_id: options.id,
        detail: _data
      });
      wx.setNavigationBarTitle({
        title: '编辑收货地址'
      });
    }
    self.BMap = new bmap.BMapWX({
      ak: util.BdKey
    });
  },
  /**
   * 展开地区选择器
   */
  selectArea: function (event) {
    let self = this;
    wx.chooseLocation({
      success(res) {
        console.log('chooseLocation',res);
        let match;
        let item = {
          longitude: res['longitude'],
          latitude: res['latitude'],
          title: res["name"],
          address: res['address'],
          area: "",
          city:"",
          province: "",
        };

        if(res.name === '我的位置'){
          item.detailinfo = res.address;
        }else{
          item.detailinfo = res.name;
        }

        self.BMap.regeocoding({
          location: item.latitude + ',' + item.longitude,
          fail: function (result) {
            console.log('fail',data);
            try{
              match = res.address.match(/市(\S*)/);
              if(match.length > 1){
                item.area = match[1];
              }
              match = res.address.match(/(\S*)省/);
              if(match.length > 0){
                item.province = match[0];
              }
              match = res.address.match(/省(\S*)市/);
              if(match.length > 1){
                item.city = match[1]+'市';
              }
            }catch (e) {

            }
            self.upAreaInfo(item);
          },
          success: function (data) {
            let _temp = data.originalData.result.addressComponent;
            item.province = _temp.province;
            item.city = _temp.city;
            item.area = _temp.district;

            self.upAreaInfo(item);

            console.log('success',data);
          },
          iconPath: '/images/icon/mark_red.png',
          iconTapPath: '/images/icon/mark_red.png'
        });
      },
      fail(res) {
        console.log('test',fail);
      }
    })
    // util.toPage('/pages/me/address/map/index');
  },

  onChange: function (event) {
    this.setData({
      'detail.gender': event.detail
    });
  },
  onSwitchChange: function ({ detail }) {
    let val = 0;
    if (detail) {
      val = 1
    }
    // 需要手动对 checked 状态进行更新
    this.setData({
      'detail.active': val
    });
  },
  addressTagclick: function (event) {
    this.setData({
      'detail.address_tag': event.currentTarget.dataset.title
    });
  },
  inputPhoneNumber (event) {

  },
  setFormValue: function (event) {
    let self = this;
    let _value = event.detail.value;
    let _detail = self.data.detail;
    let name = event.currentTarget.dataset.name;
    if (name) {
      if (_detail[name] !== _value) {
        _detail[name] = _value;
        self.setData({
          detail: _detail
        })
      }
    }
  },
  submitAddInfo: function (event) {
    let self = this;
    let _data = event.detail.value;
    let _detail = self.data.detail;
    let url = util.api.addAddress;
    if (_data.user_name === '') {
      util.msg('请填写收件人姓名!');
      return false;
    }
    if (_data.phone_number === '' || !PHOME_REG.test(_data.phone_number)) {
      util.msg('请填写正确的手机号码!');
      return false;
    }
    if (_data.detailInfo === '') {
      util.msg('请填写详情收货地址!');
      return false;
    }
    if (_detail.province === '') {
      util.msg('请选择收货地区信息!');
      return false;
    }
    _detail['user_name'] = _data.user_name;
    _detail['phone_number'] = _data.phone_number;
    _detail['detailinfo'] = _data.detailInfo;
    /**
     * 提交到服务器
     */
    if (self.data.modify === true) {
      url = util.api.editAddress;
      _detail['addr_id'] = self.data.addr_id;
    }
    util.request({
      url: url,
      data: _detail,
      callback: function (result) {
        util.msg('收货地址保存成功!');
        //返回上一页
        self.setData({
          modify: false,
          addr_id: 0
        });
        setTimeout(function () {
          wx.navigateBack();
        }, 1500);
      }
    });
  },
  delAddress: function (event) {
    let id = event.currentTarget.dataset.id;
    let self = this;
    Dialog.confirm({
      title: '操作提示',
      message: '确定要删除这个收货地址吗?'
    }).then(() => {
      util.request({
        url: util.api.delAddress,
        loading: true,
        data: {
          addr_id: id
        },
        callback: function (result) {
          if (result.status === 'ok') {
            util.msg('删除地址成功!');
            wx.navigateBack();
          }
        }
      });
    }).catch(() => {
      // on cancel
    });
  },
  upAreaInfo: function (item) {
    let setData = {};
    let address;
    address = item['address'];
    setData['detail.area_info'] = [item['province'], item['city'], item['area']].join('');
    address = address.replace(item['province'], '');
    address = address.replace(item['city'], '');
    address = address.replace(item['area'], '');
    setData['detail.longitude'] = item['longitude'];
    setData['detail.latitude'] = item['latitude'];
    setData['detail.province'] = item['province'];
    setData['detail.city'] = item['city'];
    setData['detail.county'] = item['area'];
    setData['detail.detailInfo'] = address;
    this.setData(setData);
  }
});
